<template>
    <div class="demo-Circle">
        <a-table class="file_list_table" :columns="dynamicColumns" :data-source="formattedData" bordered
            :pagination="false" :scroll="{ y: tableHeight + 'px' }" :rowClassName="rowClassName" rowKey="key"
            ref="autoScrollTable" :customRow="customRowStyle">
            <template slot="day" slot-scope="text, record">
                <a-row :gutter="[8, 8]" type="flex" :align="'top'" wrap>
                    <a-col v-for="employee in record.day" :key="employee.admitGuid" :span="4">
                        <div class="day-employee-info" :style="{ backgroundColor: employee.color }">
                            <!-- <div class="employee-info" :style="{ backgroundColor: '#CCFFFF' }"> -->
                            <!-- <a-avatar -->
                            <!-- :src="'http://182.92.209.180:39999/jeecg-boot/sys/common/static/' + employee.faceUrl" /> -->
                            <div class="info-text">
                                <p :style="{ fontSize: '10px' }">{{ employee.workNumber }}</p>
                                <p :style="{ fontSize: '8px' }">{{ employee.name }}</p>
                            </div>
                            <!-- <p>最早打卡: {{ employee.inTime }}</p>
                            <p>最晚打卡: {{ employee.outTime }}</p> -->
                        </div>
                    </a-col>
                </a-row>
            </template>
            <template slot="night" slot-scope="text, record">
                <a-row :gutter="[8, 8]" type="flex" :align="'top'" wrap>
                    <a-col v-for="employee in record.night" :key="employee.admitGuid" :span="6">
                        <div class="night-employee-info" :style="{ backgroundColor: employee.color }">
                            <!-- <div class="employee-info" :style="{ backgroundColor: '#CCFFFF' }"> -->
                            <!-- <a-avatar -->
                            <!-- :src="'http://182.92.209.180:39999/jeecg-boot/sys/common/static/' + employee.faceUrl" /> -->
                            <div class="info-text">
                                <p :style="{ fontSize: '10px' }">{{ employee.workNumber }}</p>
                                <p :style="{ fontSize: '8px' }">{{ employee.name }}</p>
                            </div>
                            <!-- <p>最早打卡: {{ employee.inTime }}</p>
                            <p>最晚打卡: {{ employee.outTime }}</p> -->
                        </div>
                    </a-col>
                </a-row>
            </template>
            <template slot="absence" slot-scope="text, record">
                <a-row :gutter="[8, 8]" type="flex" :align="'top'" wrap>
                    <a-col v-for="employee in record.absence" :key="employee.admitGuid" :span="8">
                        <div class="absence-employee-info" :style="{ backgroundColor: employee.color }">
                            <!-- <div class="employee-info" :style="{ backgroundColor: '#CCFFFF' }"> -->
                            <!-- <a-avatar -->
                            <!-- :src="'http://182.92.209.180:39999/jeecg-boot/sys/common/static/' + employee.faceUrl" /> -->
                            <div class="info-text">
                                <p :style="{ fontSize: '10px' }">{{ employee.workNumber }}</p>
                                <p :style="{ fontSize: '8px' }">{{ employee.name }}</p>
                            </div>
                            <!-- <p>最早打卡: {{ employee.inTime }}</p>
                            <p>最晚打卡: {{ employee.outTime }}</p> -->
                        </div>
                    </a-col>
                </a-row>
            </template>
        </a-table>
    </div>
</template>
<script>
import { getAction, postAction } from '../../api/manage';

export default {
    props: {
        size: {
            type: Number,
            default: 150
        }
    },
    computed: {
        // 格式化数据以适应表格的数据源格式
        formattedData() {
            return this.data.flatMap(item => {
                if (item.dept === '制造部' || item.dept == '品质技术部') {
                    return item.classes.map((cls, index) => ({
                        key: `${item.dept}_${index}`,  // 简化key生成逻辑
                        dept: index === 0 ? item.dept : '',
                        classes: cls || ' ',  // 空字符串转为空格占位
                        number: item.number[index] || '',
                        day: item.day[index] || [],
                        night: item.night[index] || [],
                        absence: item.absence[index] || [],  // 新增
                        rowSpan: index === 0 ? item.classes.length : 0
                    }));
                } else {
                    return [{
                        key: item.dept,
                        dept: item.dept,
                        classes: '',
                        number: item.number,
                        day: item.day[0] || [],
                        night: item.night[0] || [],
                        absence: item.absence[0] || [],  // 新增
                        rowSpan: 1
                    }];
                }
            });
        },
        // 动态生成表头
        dynamicColumns() {
            const updatedColumns = [...this.columns];
            // 获取当天日期并格式化
            const currentDate = new Date();
            const formattedDate = `${currentDate.getMonth() + 1}月${currentDate.getDate()}日`;
            // 找到白班列并更新其 title
            const dayColumnIndex = updatedColumns.findIndex((col) => col.key === 'day');
            if (dayColumnIndex !== -1) {
                var dayLength = this.data.reduce((sum, item) => {
                    return sum + (item.day || []).reduce((subSum, d) => subSum + d.length, 0);
                }, 0);
                updatedColumns[dayColumnIndex].title = `白班 ( ${dayLength} 人 )   ${formattedDate} 白班上班人员`;
            }
            // 找到夜班列并更新其 title
            const nightColumnIndex = updatedColumns.findIndex((col) => col.key === 'night');
            if (nightColumnIndex !== -1) {
                var nightLength = this.data.reduce((sum, item) => {
                    return sum + (item.night || []).reduce((subSum, n) => subSum + n.length, 0);
                }, 0);

                // 新增日期判断逻辑
                const now = new Date();
                const targetDate = new Date(now);
                if (now.getHours() < 12) {
                    targetDate.setDate(targetDate.getDate() - 1); // 12点前使用昨日日期
                }
                const nightDate = `${targetDate.getMonth() + 1}月${targetDate.getDate()}日`;

                updatedColumns[nightColumnIndex].title = `夜班 ( ${nightLength} 人 )   ${nightDate} 夜班上班人员`;
            }
            // 新增欠勤列动态人数
            const absenceColumnIndex = updatedColumns.findIndex((col) => col.key === 'absence');
            if (absenceColumnIndex !== -1) {
                var absenceLength = this.data.reduce((sum, item) => {
                    return sum + (item.absence || []).reduce((subSum, a) => subSum + a.length, 0);
                }, 0);
                updatedColumns[absenceColumnIndex].title = `未出勤( ${absenceLength} 人 )`;
            }
            return updatedColumns;
        },
    },
    data() {
        return {
            tableHeight: this.calculateTableHeight(), // 初始化表格高度
            columns: [
                {
                    title: '部门',
                    dataIndex: 'dept',
                    key: 'dept',
                    width: 93,
                    customRender: (value, row, index) => {  // 新增合并单元格渲染逻辑
                        return {
                            attrs: { rowSpan: row.rowSpan },
                            children: value
                        };
                    }
                },
                {
                    title: '课',
                    dataIndex: 'classes',
                    key: 'classes',
                    width: 93,
                },
                {
                    title: '在职人数',
                    dataIndex: 'number',
                    key: 'number',
                    width: 79,
                },
                {
                    title: '白班',
                    key: 'day',
                    scopedSlots: { customRender: 'day' },
                },
                {
                    title: '夜班',
                    key: 'night',
                    scopedSlots: { customRender: 'night' },
                    width: 270,
                },
                {
                    title: '未出勤',
                    key: 'absence',
                    scopedSlots: { customRender: 'absence' },
                    width: 200,
                },
                {
                    title: '长期休假(0人)',
                    key: 'leave',
                    width: 125,
                },
            ],
            data: [],
            schedulingInterval: null,
            admitGuidInterval: null,
            isAutoScrolling: false, // 控制自动滚动的状态
            url: {
                getTodayScheduling: '/clockRecord/clockRecord/today',
            },
        };
    },
    created() {
        this.getTodayScheduling() // 立即获取当天调度信息
        this.startIntervals() // 启动定时器
    },
    mounted() {
        window.addEventListener('resize', this.updateTableHeight);
        // 初始化时调用一次，确保初始状态下表格高度正确
        this.updateTableHeight();
        // this.startAutoScroll()
    },
    methods: {
        getTodayScheduling() {
            postAction(this.url.getTodayScheduling, this.getDataTemplete()).then((res) => {
                console.log(res.result)
                this.data = res.result
            })
        },
        startIntervals() {
            // 设置每分钟调用一次 getTodayScheduling()
            this.schedulingInterval = setInterval(() => {
                this.getTodayScheduling();
            }, 10000); // 10秒
        },
        clearIntervals() {
            if (this.schedulingInterval) {
                clearInterval(this.schedulingInterval);
            }
            if (this.admitGuidInterval) {
                clearInterval(this.admitGuidInterval);
            }
        },
        rowClassName(record, index) {
            return index % 2 == 0 ? "first" : "second";
        },
        startAutoScroll() {
            if (this.isAutoScrolling) return;
            const tableBody = this.$refs.autoScrollTable.$el.querySelector('.ant-table-body');
            if (!tableBody) return;

            // 检查是否在顶部，如果是则等待几秒钟再开始滚动
            if (tableBody.scrollTop === 0) {
                setTimeout(() => {
                    this._startScrollLoop(tableBody);
                }, 2000); // 在顶部停留 2 秒钟
            } else {
                this._startScrollLoop(tableBody);
            }
        },
        _startScrollLoop(tableBody) {
            this.scrollInterval = setInterval(() => {
                // 定义一个小的容差值用于浮点数比较
                const tolerance = 1;
                // 检查是否到达底部或接近底部
                if (Math.abs(tableBody.scrollTop + tableBody.clientHeight - tableBody.scrollHeight) < tolerance) {
                    // 停止当前滚动
                    this.stopAutoScroll();
                    // 设置延时，2秒后回到顶部
                    setTimeout(() => {
                        tableBody.scrollTop = 0; // 返回顶部
                        this.startAutoScroll(); // 重新开始滚动
                    }, 2000); // 2 秒
                } else {
                    tableBody.scrollTop += 1; // 每次增加 5px
                }
            }, 10); // 每秒滚动一次
            this.isAutoScrolling = true;
        },
        stopAutoScroll() {
            if (this.scrollInterval) {
                clearInterval(this.scrollInterval);
                this.scrollInterval = null;
                this.isAutoScrolling = false;
            }
        },
        calculateTableHeight() {
            // 计算表格应有的高度，这里假设除了表格外，页面顶部有100px的其他元素
            return window.innerHeight - 150;
        },
        updateTableHeight() {
            this.tableHeight = this.calculateTableHeight();
        },
        customRowStyle(record) {
            return {
                style: {
                    padding: '0px !important', // 强制覆盖行内样式
                }
            };
        },
        getDataTemplete() {
            return [
                {
                    dept: "社长",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
                {
                    dept: "管理部",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
                {
                    dept: "营业部",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
                {
                    dept: "财务课",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
                {
                    dept: "内部统制部",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
                {
                    dept: "运营部",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
                {
                    dept: "制造统括部",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
                {
                    dept: "环境安全部",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
                {
                    dept: "制造部",
                    classes: ['', '冲压课', '电镀课', '制品检查课', '水处理课', '模具维护课', '设备课'],
                    number: [0, 0, 0, 0, 0, 0, 0],
                    day: [[], [], [], [], [], [], []],
                    night: [[], [], [], [], [], [], []],
                    absence: [[], [], [], [], [], [], []],
                    leave: [[], [], [], [], [], [], []],
                },
                {
                    dept: "品质技术部",
                    classes: ['', '品质管理课'],
                    number: [0, 0],
                    day: [[], []],
                    night: [[], []],
                    absence: [[], []],
                    leave: [[], []],
                },
                {
                    dept: "品质保证部",
                    classes: [],
                    number: [''],
                    day: [[]],
                    night: [[]],
                    absence: [[]],
                    leave: [[]],
                },
            ]
        }
    },
    beforeDestroy() {
        this.clearIntervals(); // 清除定时器
        this.stopAutoScroll();//停止自动滚动
        // 清除监听器以避免内存泄漏
        window.removeEventListener('resize', this.updateTableHeight);
    },
}
</script>
<style lang="less">
// 全局覆盖Ant Design表格样式（移除scoped）
.file_list_table .ant-table {

    &-thead>tr>th,
    &-tbody>tr>td,
    &-cell {
        padding-top: 5px !important;
        padding-bottom: 6px !important;
        padding-left: 6px !important;
        padding-right: 6px !important;
    }
}

.info-text {
    flex: 1; // 新增
    display: flex;
    flex-direction: column;
    justify-content: space-around; // 改为等间距分布
    align-items: center; // 新增水平居中
    padding-top: 0px !important;
    padding-bottom: 0px !important;
    height: 100%; // 确保填满父容器
}

.info-text p {
    margin: 0px;
    padding: 0px;
    display: flex;
    justify-content: center; // 文字水平居中
    align-items: center; // 文字垂直居中
    width: 100%; // 占满父容器宽度
    height: 100%; // 占满父容器高度
}
</style>

<style lang="less" scoped>
.day-employee-info {
    display: flex;
    // background-color: #1871cb;
    /* 与表格背景一致 */
    border-radius: 8px;
    color: #000;
    width: 80px;
    padding-top: 0px !important;
    padding-bottom: 0px !important;
    margin: 0px;
    text-align: center;
}

.night-employee-info {
    display: flex;
    // background-color: #1871cb;
    /* 与表格背景一致 */
    border-radius: 8px;
    color: #000;
    width: 60px;
    padding-top: 0px !important;
    padding-bottom: 0px !important;
    margin: 1px;
}

.absence-employee-info {
    display: flex;
    // background-color: #1871cb;
    /* 与表格背景一致 */
    border-radius: 8px;
    color: #000;
    width: 60px;
    padding-top: 0px !important;
    padding-bottom: 0px !important;
    margin: 1px;
}

/* 设置栅格系统中每一栏的宽度 */
.ant-col {
    display: flex;
    flex-direction: column;
    padding-top: 1px !important;
    padding-bottom: 1px !important;
}
</style>